public with sharing class AdjustTaskAmountController {

	public String taskId {get;set;}
	public String dataJson {get;private set;}
	public String msg {get;private set;}
	public Boolean isSuccess {get; private set;}

	public String saveJson {get;set;}
    public AdjustTaskAmountController() {
        taskId = System.currentPageReference().getParameters().get('id');
    }

    ///获取当前时间以后的任务量
    public void getTasks(){

    	List<TaskBean>  tmp = new List<TaskBean>();
    	String  year = String.valueOf(System.now().year())+'年';
        Set<String> month = new Set<String>();

        for(Integer i = System.now().month() ; i <=12 ; i ++){
            
            month.add(String.valueOf(i));
        }
        Map<String ,TaskBean> adMap = new Map<String ,TaskBean>();
        Map<String ,TaskBean> eMap = new Map<String ,TaskBean>();
    	for(TaskAmount__c ta : [select Id,Year__c,Month__c,Brand__c,AssignAmount__c,Category1__c,Category2__c,IsAdjust__c
		 from TaskAmount__c where  Standers__c =: taskId and (Year__c >:year Or (Year__c =:year and Month__c in: month)) order by Brand__c,Category1__c,Category2__c, Year__c,Month__c ]){

    		tmp.add( new TaskBean(ta));


    		String key = ta.Category1__c +'_'+ta.Brand__c +'_'+ta.Category2__c + '_'+ta.Year__c + '_'+ ta.Month__c;
			if(ta.IsAdjust__c == true){
				TaskBean ad = new  TaskBean(ta) ;


				if(adMap.get(key) != null)ad.taskAmount += adMap.get(key).taskAmount;
					
				
				
				adMap.put(key,ad);
			}else{
				eMap.put(key, new TaskBean(ta));
			}
    	}

    	for (String key  : adMap.keySet()) {
    		if(eMap.containsKey(key)){
    			TaskBean t = eMap.get(key);
    			t.adtaskAmount = adMap.get(key).taskAmount;
				t.adId = adMap.get(key).tid;

    		}
    	}
    	dataJson = EncodingUtil.urlEncode(JSON.serialize(eMap.values()), 'UTF-8');


    }

    public void save (){
    	msg = '';
    	List<Object> resList=(List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
            if(resList.size() > 0){
                List<TaskAmount__c> asInsList = new List<TaskAmount__c>();

                for (Object res : resList) {
                    Map<String ,Object> o = (Map<String ,Object> )res;
                    TaskAmount__c t = new TaskAmount__c();
					t.Year__c = String.valueOf(o.get('year'));
					t.Month__c = String.valueOf(o.get('month'));
					t.Category1__c = String.valueOf(o.get('cate1'));
					t.Category2__c = String.valueOf(o.get('cate2'));
					t.Brand__c = String.valueOf(o.get('brand'));
					t.AssignAmount__c = getDecimalValue(o.get('adtaskAmount'));
					t.Standers__c  = taskId;
					t.IsAdjust__c = true;
					if(o.get('adId') != null)t.Id = String.valueOf(o.get('adId'));
                    asInsList.add(t);

                }
                SavePoint sp = Database.setSavepoint();
                try {
                    upsert  asInsList;
                    isSuccess = true;
                    msg = '保存成功!';
                }catch (Exception e) {
                	isSuccess = false;
                    Database.rollback(sp);
                    msg = '保存失败! '+e.getMessage();
                }
                
                 

            }


    }
    private Decimal getDecimalValue(Object val){
        if(val == null)return null;
        String  d = String.valueOf(val);
        if(d == '')return null;
        return Decimal.valueOf(d.trim());
    }
    public void setNil(){
    	dataJson = '';
    	saveJson = '';
    }


     private Class TaskBean{
        public String tid;
    	public String cate1 ;//分类
    	public String year ;//年
    	public String month;//月
    	public Decimal taskAmount ;//任务量
    	public String cate2;
    	public String brand ;
    	public Decimal adtaskAmount ; //调整任务量
    	public String type ;
    	public String adId ;//调整ID

    	public TaskBean(TaskAmount__c ta){
            tid = ta.Id;
    		cate1 = ta.Category1__c;
    		cate2 = ta.Category2__c;
    		month = ta.Month__c;
    		year = ta.Year__c;
    		brand = ta.Brand__c;
    		taskAmount = ta.AssignAmount__c == null ? 0 : ta.AssignAmount__c.setScale(2, RoundingMode.HALF_UP);
    		adtaskAmount = 0;
    	}
    }



}